import * as yaml from 'js-yaml'; 
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'

 

const CACHE = new Map<string, object>()
/**
 * @description 载入dir路径下的yaml配置文件 
 * @author created by 孔东
 * @date 2024-02-22 10:11:24
 * @param {string} dir 文件夹路径
 */
function load(_dir: string) {
    const dir = join(_dir, './yaml') 
    return () => {
        const env = process.env.NODE_ENV || 'development'
        const fileKeys = ['.yaml', `${env}.yaml`].map(file => join(dir, file)).filter(file => existsSync(file))
        const cacheKey = fileKeys.join(',')
        const cacheConfig = CACHE.get(cacheKey)
        if(cacheConfig) {
            return cacheConfig
        }
        let config = fileKeys.reduce((config, file) => ({ ...config, ...yaml.load(readFileSync(file, { encoding: 'utf-8' }))}), {})
        console.log('>>> 配置载入成功 <<<')
        console.log(config)
        CACHE.set(cacheKey, config)
        return config;
    }
};
export default load